// pages/user-auth/user-auth.js
Page({
  data: {
    username: '', // 存储输入的用户名
    phoneNumber: '', // 存储输入的手机号
    isPhoneNumberError: false, // 标记手机号是否有误
    isFormComplete: false, // 标记表单是否填写完整
    items: [
      { id: 1, name: "《用户服务协议》及《隐私政策》", checked: false },
    ],
    content: '18588957023',
    add: '广东省中山市三乡镇碧华大道16号·梵英超声',
    demand: '',
  },

  onShow() {
    let demand = wx.getStorageSync('demand');
    let username = wx.getStorageSync('username');
    let phoneNumber = wx.getStorageSync('phoneNumber');
    this.setData({
      demand: demand,
      username: username,
      phoneNumber: phoneNumber,
    });

    let privacy = wx.getStorageSync('hasAgreedPrivacy');
    if (privacy === true) {
      this.setData({
        'items[0].checked': true
      })
    }
  },


  handleInputDemand(e) {
    const value = e.detail.value;
    this.setData({
      demand: value,
    });
  },


  handleInputUsername(e) {
    const value = e.detail.value;
    this.setData({
      username: value,
    });
  },


  handleInputPhone(e) {
    const value = e.detail.value;
    this.setData({
      phoneNumber: value,
    });

    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    const isPhoneNumberError = !phoneRegex.test(value);
    if (value.length > 10) {
      this.setData({
        isPhoneNumberError: isPhoneNumberError, // 更新手机号错误标记
        isFormComplete: this.data.username && this.data.phoneNumber && !isPhoneNumberError, // 更新表单完整标记
      });
    }

  },

  handleItemTap(e) {
    const id = e.currentTarget.dataset.id;
    const items = this.data.items.map(item => {
      // 当前点击的选项切换选中状态
      if (item.id === id) {
        return { ...item, checked: !item.checked };
      }
      // 其他选项取消选中（保证单选）
      return { ...item, checked: false };
    });
    this.setData({ items });

    // 获取当前选中的值（可选）
    const selectedItem = items.find(item => item.checked);
    console.log("当前选中:", selectedItem ? selectedItem.id : null);
  },

  submitForm() {

    if (this.data.isPhoneNumberError) {
      wx.showToast({
        title: '手机号格式错误',
        icon: 'none',
        duration: 2000,
      });
      return;
    };

    if (this.data.items[0].checked === false) {
      wx.showToast({
        title: '请同意用户隐私协议',
        icon: 'none',
        duration: 2000,
      });
      return;
    };

    // 将表单数据提交到云数据库
    wx.cloud.database().collection('users').add({
      data: {
        username: this.data.username,
        phoneNumber: this.data.phoneNumber,
        demand: this.data.demand,
      },
      success: res => {
        wx.showToast({
          title: '提交成功',
          icon: 'success'
        })
        this.setData({
          username: '',
          phoneNumber: '',
          demand: '',
        }),
          wx.switchTab({
            url: 'pages/home/home',
          });
      },
      fail: err => {
        wx.showToast({
          title: '提交成功',
          icon: 'error'
        })
        console.error('表单数据提交失败', err);
      }
    });
  },

  handlePrivacy() {
    wx.setStorageSync('demand', this.data.demand);
    wx.setStorageSync('username', this.data.username);
    wx.setStorageSync('phoneNumber', this.data.phoneNumber);

    wx.navigateTo({
      url: `/pages/privacy/privacy`
    });
  },

  onShareAppMessage() {

  },
  onShareTimeline() {
    return {
      title: '梵英超声技术有限公司',
    }
  },
  onCopy(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.text.toString(),
      success: function () {
        wx.showToast({ title: '复制成功' });
      }
    });
  },

  longPressHandler(e) {
    wx.scanCode({
      scanType: ['qrCode'],
      success(res) {
        console.log('识别结果', res.result)
      }
    })
  }
}) 
